'use client';

import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/Popover';
import { trpcPureClient } from '@/utils/api';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Plus } from 'lucide-react';
import { use, useState } from 'react';

export default function ApiKeyPage({
  params,
}: {
  params: Promise<{
    id: string;
  }>;
}) {
  const { id } = use(params);
  const queryClient = useQueryClient();
  const { data: apiKeys } = useQuery({
    queryKey: ['apiKeys'],
    queryFn: async () => {
      return trpcPureClient.apiKeys.listApiKeys.query({ appId: id });
    },
    enabled: Boolean(id),
  });

  const { mutate } = useMutation({
    mutationFn: async (name: string) => {
      return trpcPureClient.apiKeys.createApiKey.mutate({
        appId: id,
        name,
      });
    },
    onSuccess(data) {
      setNewApiKeyName('');
      queryClient.setQueryData(['apiKeys'], (prev: typeof apiKeys) => {
        if (!prev || !data) return prev;

        return [data, ...prev];
      });
    },
  });

  const [newApiKeyName, setNewApiKeyName] = useState('');

  return (
    <div className="container pt-10 mx-auto">
      <div className="flex justify-between items-center">
        <h1 className="text-3xl mb-6">Api Keys</h1>
        <Popover>
          <PopoverTrigger asChild>
            <Button>
              <Plus />
            </Button>
          </PopoverTrigger>
          <PopoverContent>
            <div className="flex flex-col gap-4">
              <Input
                placeholder="Name"
                value={newApiKeyName}
                onChange={(e) => {
                  setNewApiKeyName(e.target.value);
                }}
              ></Input>
              <Button
                type="submit"
                disabled={newApiKeyName.length < 3}
                onClick={() => {
                  mutate(newApiKeyName);
                }}
              >
                Submit
              </Button>
            </div>
          </PopoverContent>
        </Popover>
      </div>
      {apiKeys?.map((api) => {
        return (
          <div
            key={api.id}
            className="border p-4 flex justify-between items-center"
          >
            <span>{api.name}</span>
            <span>{api.key}</span>
          </div>
        );
      })}
    </div>
  );
}
